<template>
    <div id="p_timepro" class="p_task">
    <actionsheet v-model="showEditBtn" :menus="asBtnCurr" show-cancel @on-click-menu="chooseEdit"></actionsheet>  
    <!-- 可以添加像饿了么左右分栏的方式来管理显示多个成员的任务. -->
    <div style="display:flex">
        <div style="width: 100%;overflow:scroll;-webkit-overflow-scrolling:touch;background-color:#fff;"> 
          <tab class="day" :style="{width: projects.length*90 +'px'}" bar-active-color="#37aefc" :line-width="0">
            <tab-item @on-item-click="onProj(it,index)" :selected="index === proIndex" active-class="active-tab" :value="it" v-for="(it, index) in projects" :key="index">{{it.title.length<5?it.title:it.title.substr(0,4)+'..'}}</tab-item>  
          </tab>
        </div>
        <button-tab v-model="editType"  style="width:150px;">
            <button-tab-item @on-item-click="toEditProject(0)" >创建</button-tab-item>
            <button-tab-item @on-item-click="toEditProject(1)" >设置</button-tab-item>
            <!--<button-tab-item @on-item-click="onTaskAdd">任务+</button-tab-item>--> 
        </button-tab>
    </div>
  <x-progress :percent="taskPercent" :show-cancel="false"></x-progress>
  <div class="good" v-if="showMode != 'default'" :style="{height:taskHeight+'px'}" v-show="editType!=0">
    <div class="menu-wrapper" ref="menuWrapper">
      <ul>
        <li v-for="(item, index) in menuTasks" ref="menu" :tagkey="item.key" :tagValue="item.value" class="menu-item border-1px" :class="{'current':currentIndex === index}"
            @click="selectMenu(index, $event)">
          <span class="text">
          <div class="iconMenu">
              <img src="/static/z39h5/img/logo.png" style="width:56px;height:56px;"/>
              <span style="position:absolute;top:0;left:0;border-radius: 4px 0 4px 0;background-color: #f4ad50">{{item.done +'/'+ (item.undo +item.done)}}</span>
              <span style="position:absolute;bottom:6px;left:0;width: 100%;text-align: center;border-radius: 0 0 4px 4px;background-color: rgba(14, 154, 226, 0.73);height:14px; overflow:hidden;">{{item.name}}</span>
          </div>
          </span>
        </li>
      </ul>
    </div>
    <div class="foods-wrapper" ref="foodWrapper">
      <ul>
        <li v-for="(group, index1) in menuTasks" class="food-list food-list-hook">            
          <h1 class="title">{{group.name}}</h1>
                <group>
                    <swipeout>
                        <swipeout-item @on-open="actionOpenDone(item, index,1, index1)" v-for="(item, index) in group.tasks" :key="index" :ref="'actionUser'+index1" @longtap="doLongtap">
                            <div slot="right-menu">
                                <swipeout-button @click.native="onDelClick(item,index)" type="warn">取消</swipeout-button>
                                <swipeout-button @click.native="goTask(item,index)" type="primary">详情</swipeout-button>
                                <swipeout-button @click.native="onTaskDue(item,index)" type="warn">{{dayshow(item,daySwipe)}}</swipeout-button>
                            </div>
                            <div slot="left-menu">
                                <swipeout-button type="primary">{{item.state!='done'?'完成':'取消完成'}}</swipeout-button>
                            </div>
                            <div slot="content" class="vux-1px-t" v-bind:class="{task_going:item.state=='started',task_done:item.state=='done',task_toggle:item.state=='toggle',task_cancle:item.state=='cancelled',task_curr: taskCurr == item}" @touchstart="doTaskTouchStart(item,index)">
                                <cell @click.native="onAction(item,index1)" :title="(index+1) +'.'+ showDue(item) +item.title" :inline-desc="item.desc">
                                </cell>
                            </div>
                        </swipeout-item>
                    </swipeout>
                </group>

          <!-- <ul>
            <li v-for="(task,index) in item.tasks" @click="onAction(task)" class="food-item">
              <div class="content">
                <h2 class="name" v-bind:class="{task_going:task.state=='started',task_done:task.state=='done',task_cancle:task.state=='cancelled'}">{{(index+1)+'.'+task.title}}</h2>
                <p v-if='task.desc' class="desc">{{task.desc}}</p>
              </div>
            </li>
          </ul> -->
        </li>
      </ul>
    </div>
  </div>
    <scroller v-show="showMode == 'default'" v-model="pullStatus" lock-x scrollbar-y :pulldown-config="pullDownConfig2" use-pullup :pullup-config="pullupConfig2" :height="scrollHeight" ref="scroll" @on-pullup-loading="loadNext" :scroll-bottom-offset="300">
                <group  class="group0" v-show="editType!=0">
                <div v-if="proTasks.length==0" style="text-align:center;" ><img src="/static/z39h5/img/none.png" width="200" /></div>
                    <swipeout v-if="showMode == 'default'">
                        <swipeout-item v-if="index<pageShowNum" @on-open="actionOpenDone(item, index,2)" v-for="(item, index) in proTasks" :key="index" ref="action" @longtap="doLongtap">
                            <div slot="right-menu">
                                <swipeout-button @click.native="onDelClick(item,index)"  type="warn">取消</swipeout-button>
                                <swipeout-button @click.native="goTask(item,index)" type="primary">详情</swipeout-button>
                                <swipeout-button @click.native="onTaskDue(item,index)" type="warn">{{dayshow(item,daySwipe)}}</swipeout-button>
                            </div>
                            <div slot="left-menu">
                                <swipeout-button type="primary">{{item.state!='done'?'完成':'取消完成'}}</swipeout-button>
                            </div>
                            <div slot="content" class="vux-1px-t" v-bind:class="{task_going:item.state=='started',task_done:item.state=='done',task_toggle:item.state=='toggle',task_cancle:item.state=='cancelled',task_curr: taskCurr == item}" @touchstart="doTaskTouchStart(item,index)">
                                <cell @click.native="showTasnBtn(item)" :title="showDue(item) +item.title" :value="item.duration" :inline-desc="item.desc">
                                  <div slot="icon">
                                      <img :src="showIcons(item)" style="width:50px;height:50px;"/>
                                      <span class="taskCount">{{index+1 + "/" + tasksLenStr}}</span>
                                  </div>
                                </cell>
                            </div>
                        </swipeout-item>
                    </swipeout>
                </group>
    <div slot="pullup" class="xs-plugin-pullup-container xs-plugin-pullup-up" style="position: absolute; width: 100%; height: 40px; bottom: -40px; text-align: center;">
        <span v-show="pullStatus.pullupStatus === 'default'"></span>
        <span class="pullup-arrow" v-show="pullStatus.pullupStatus === 'down' || pullStatus.pullupStatus === 'up'" :class="{'rotate': pullStatus.pullupStatus === 'up'}">Loading</span>
        <span v-show="pullStatus.pullupStatus === 'loading'"></span>
      </div>
    </scroller>
         <popup v-model="showMember" position="bottom">
                <divider>设置成员</divider>
                  <checker class="checkScroll" v-model="taskMember" default-item-class="demo1-item" type="checkbox" :max="1" selected-item-class="demo1-item-selected">
                    <checker-item v-for="(it, index) in members" :key="index" :value="it">{{it.nname||it.username}}</checker-item>
                </checker>                
                <div class="spacer_v"></div>
            </popup>
         <popup v-model="showDepart" position="bottom">
            <divider>设置部门</divider>
              <checker class="checkScroll" v-model="taskDepart" default-item-class="demo1-item" type="checkbox" :max="1" selected-item-class="demo1-item-selected">
                <checker-item v-for="(it, index) in departs" :key="index" :value="it">{{it.name}}</checker-item>
            </checker>                
            <div class="spacer_v"></div>
        </popup>
        <task-add :show="showTaskAdd" :ext="taskAddExt" v-on:toVisible="taskAddVis"></task-add>
    </div>
</template>
<script>
import moment from "moment";
import _ from 'underscore' ;

import BScroll from 'better-scroll';
import { taskAndTag  } from "../mixin";
import { help  } from "../mixinApp";
import TaskAdd from "../TaskAdd";

import api from '../../api';
import {mapState,mapActions} from 'vuex'

let noneUser = {name:"未分类",show:"",undo:0,done:0, key:"to",value:0,fuid:0,img:'',tasks:[]} ;
let noneTag = {name:"未分类",show:"",undo:0,done:0,key:" ",value:0,uid:0,img:'',tasks:[]} ;
let memberDic ={},departDic={},memberBefore,departBefore;

import {
    Toast,Swipeout,SwipeoutItem,SwipeoutButton,XButton,Group,Cell,Tab,TabItem,XProgress,Popup,Checker,CheckerItem,Divider,Actionsheet,
    Box,XInput,XTextarea,Flexbox, FlexboxItem,Datetime,Scroller,ButtonTab,ButtonTabItem
} from 'vux'

export default {
    components: {
        Toast,Swipeout,SwipeoutItem,SwipeoutButton,XButton,Group,Cell,Tab,TabItem,XProgress,Popup,Checker,CheckerItem,Divider,TaskAdd,Actionsheet,
    Box,XInput,XTextarea,Flexbox, FlexboxItem,Datetime,Scroller,ButtonTab,ButtonTabItem
    },
    mixins: [taskAndTag,help],    
    computed: {
        proTasks:function(){
            if( this.proCurr == null ) return [] ;
            console.log("proTasks in");
            let pid = this.proCurr.id ;
            let temp = this.taskAll.filter(task=>{return task.pid == pid && task.parid == null } );
            this.tasksLen = temp.length ;
            this.tasksLenStr = this.tasksLen<1000?(""+this.tasksLen):(Math.ceil(this.tasksLen/100)/10+"k")
            this.pageTotal = this.tasksLen / this.pageNumOne ;
            return temp;
        },
        menuTasks:function(){
            let res ;
            if( this.showMode == 'default' ){
                return [] ;
            }
            if( this.menuUserDic == null || this.menuTagDic==null){
                console.log("menu task not ready");
                return [] ;
            }

            var tempMenu = [];

            let tagsArr = this.tagsArr ;
            let tmptags = this.tmptags ;

            var task , temp , keys ,hasKeys ,tempKey,menuTagDic,menuUserDic ;

            if(this.showMode == 'user'){
                menuUserDic = menuUserDic || Object.assign({},this.menuUserDic) ;
                for(var key in menuUserDic){
                    var item = menuUserDic[key] ;
                    item.tasks=[];
                    tempMenu.push(item) ;
                }
                tempMenu = _.sortBy(tempMenu, function(item){ return Math.max(item.uid); });
            }else if(this.showMode == 'project'){
                menuTagDic = menuTagDic || Object.assign({},this.menuTagDic) ;
                for(var key in menuTagDic){
                    var item = menuTagDic[key] ;
                    item.tasks=[];
                    tempMenu.push(item) ;
                }
            }
            let tempi = 0 ;
            // 计算分类中的任务 完成和未完成任务, 计数归0.
            if( this.showMode == 'user'){
                for(var key in menuUserDic){
                    temp =  menuUserDic[key] ;
                    temp.done = 0 ;
                    temp.undo = 0 ;
                    if(key > 0 && tempi ==0){
                        this.memberSelect = this.memberSelect || key ;
                        tempi ++ ;
                    }
                }
            }else if(this.showMode == 'project'){                
                for(var key in menuTagDic){
                    temp =  menuTagDic[key] ;
                    temp.done = 0 ;
                    temp.undo = 0 ;
                    if(key.length>1 && tempi ==0){
                        this.departSelect = this.departSelect || key ;
                        tempi ++ ;
                    }                    
                }
            }
            let doneAll = 0 ,taskAll = 0 ;
            let pid = this.proCurr.id ;
            let pTasks = this.taskAll.filter(task=>{return task.pid == pid && task.parid == null} )
            var len = pTasks.length ;
            for(var i=0;i<= len-1 ;i++){                
                task = pTasks[i] ;
                if( this.showMode == 'user'){                    
                    temp = menuUserDic[task.uid] || menuUserDic[0];
                    temp.tasks.push(task);
                }else if(this.showMode == 'project'){
                    keys = _.keys(task.tags) ;
                    hasKeys = _.intersection(keys,tagsArr);
                    tempKey = hasKeys.length >0 ? hasKeys[0]:" " ;
                    temp = menuTagDic[tempKey] ;
                    temp.tasks.push(task);
                }
                
                if( task.state =='done' || task.state =='cancelled'){
                    temp.done ++ ;
                    doneAll ++ ;
                }else{
                    temp.undo ++ ;
                }
            }
            taskAll = len ;
            this.changePercent(doneAll,taskAll) ;
            // console.log("menuTasks in ",pid,pTasks.length,menuUserDic,menuTagDic,tempMenu);
            console.log("select:",this.memberSelect, this.departSelect);
            setTimeout(()=>{
              let y = this.foodScroll ?this.foodScroll.y : 0;
              this.refreshList(y)},10);
            return tempMenu ;
        },
        ...mapState({
            isNavShow: state => state.vux.isNavShow,
            uid: state => state.vux.uid,
            taskAll: state => state.z39.taskAll,
            tagDic: state => state.z39.tagDic,
            
            tagitems: state => state.z39.tagitems,
            tagitemDic: state => state.z39.tagitemDic,
            projects:state => state.z39.projects,
            memberDic: state => state.z39.memberDic,
            taskRunId: state => state.z39.taskRunId,
            taskRunTitle: state => state.z39.taskRunTitle,
        })
    },
    watch: {
        "showMember":function(){
            if( !this.showMember ){
                let select,uid ;
                if(this.taskMember.length>0 &&this.taskMember[0]){
                    select = this.taskMember[0];
                    uid = select.fuid||select.uid ;
                }else uid = null ;
                if( memberBefore == uid) return ;                
                let _this = this ;
                this.taskSet({id:this.taskCurr.id,uid}, this.taskCurr).then(data=>{this.refreshUser(this.taskCurr)});
                // this.doTagSet(this.taskCurr,"to",select.uid);
                this.memberSelect = uid ;
                // console.log("show:",this.taskMember) ;
            }else{
                this.taskMember = this.taskCurr.uid?[memberDic[this.taskCurr.uid]]:[];
                memberBefore = this.taskCurr.uid||null;
            }
        },
        "showDepart":function(){
            let select,key ;
            if( !this.showDepart ){
                key = this.taskDepart.length>0?this.taskDepart[0].key:null ;
                if( departBefore == key ) return ;
                let _this = this ;
                if(key) this.doTagSet(this.taskCurr,key,"");
                else this.tagsDel([departBefore],false,this.taskCurr);
                this.departSelect = key ;
                console.log("show:",select,this.taskDepart) ;
            }else{
                this.taskDepart = [];
                var tags = this.taskCurr.tags ;
                if(tags){
                    for(var k in tags) {
                        if(departDic[k]) {
                            key = k;
                            break;
                        }
                    }
                }
                this.taskDepart = key?[departDic[key]]:[];
                departBefore = key||null;
            }
        },
        "projects":function(){
            var index = 0 ;
            var old = parseInt(localStorage.getItem("projectSelect")) || this.proIndex || 0 ;
            if( old <= this.projects.length -1 ){
                index = old ;
            }else if( old-1 > 0){
                index = old-1 ;
            }else{
                index = 0 ;
            }
            this.onProj( this.projects[index ],index );
        },
        // "keySet":function(){ //奇怪的没触发逻辑.
        // }
    },
    filters:{
    },
    activated () {
        // console.log("activated")
        this.showMode = window.localStorage.getItem('project_mode'+this.proCurr.id) || 'default';
    },
    created() {        
        this.dueSelect = moment().format('YYYY-MM-DD') ;
        this.memberlist = this.memberlist.concat( this.memberBtn ) ;
        this.taskHeight=(window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight) - (this.isNavShow?130:76);        
        this.scrollHeight = this.isNavShow?"-129":(-129+55+"");
        // console.log("this.taskHeight:",this.taskHeight,this.isNavShow?130:(130-55));
    },
    mounted: function() {
        this.initPage();
        this.$vux && this.$vux.bus && this.$vux.bus.$on('loginDone', this.initPage);
    },
    methods: { 
        initPage(){
			if( this.uid == 0 ) {                
                this.onProj(this.projects[0],0) ;
                this.showMode = 'default' ;
                return ;
            }
            var selected = parseInt(localStorage.getItem("projectSelect")) || 0 ;
            console.log("selected",selected);
            if( this.projects.length > 0 && !this.inited){
                this.onProj(this.projects[selected],selected) ;
                this.inited = true ;
            }            
        }   ,    
        doTaskAdd(){
            let data ;
            if( this.taskTitle.length == 0 ) return ;

            data = {title:this.taskTitle} ;
            data.desc = this.taskDesc || "" ;
            data.pid = this.proCurr.id ;
            let tags = {created:moment().format('YYYY-MM-DD HH:mm')} ;
            if( this.keySet == 'to'){
                if( this.uidSet != 0 ){
                    // tags.to = this.uidSet || this.uid ;
                    data.uid = this.uidSet || this.uid ;
                }
            }else{
                if( !_.isEmpty(this.keySet) ){
                    tags[this.keySet] = '' ;
                }
            }
            this.taskAdd(data, tags,true).then(data => { this.resetInput() }); //不自动在前端添加uid
        },
        resetInput(){            
            this.taskTitle="";
            this.taskDesc="";
            this.proTitle="";
            this.prokey="";
            this.proDesc="";
        },
        toEditProject(type){            
            // setTimeout(()=>{this.editType = -1},10);
            if(this.$route.path.indexOf("m_task")==-1 && !this.uid && !localStorage.getItem('token')) return this.$vux && this.$vux.bus && this.$vux.bus.$emit('showlogin', true);
            this.editType = -1 ;
            let gid = this.proCurrData.id ;
            if(type==0){
                this.go(`tproject`);
            }else{
				if(!gid) return this.$vux.toast.show({text:"请选中项目" ,type: 'warn'});
                this.go(`tproject?gid=${gid}`);
            }            
        },
        doTaskCancle(){
            this.editType = -1 ;
        },
        onDelClick(item, index) {
            this.doTaskEdit(item,"cancelled",moment().format("YYYY-MM-DD HH:mm"));
        },
        onProj(item,index){            
            if(this.proCurr == item || !item) return ;
            if(this.uid != 0) localStorage.setItem("projectSelect",index);
			this.taskAddExt = {pid:item.id}; //给添加任务设置pid,
			this.$store.commit({ type: "z39/addTaskExt", value: {pid:item.id} });

            this.proCurr = item ;
            this.proIndex = index ;
            this.showMode = window.localStorage.getItem('project_mode'+this.proCurr.id) || 'default';
            console.log("this.proIndex:",this.proIndex)
            this.proCurrData = Object.assign({}, item) ;
            this.$store.commit('z39/proCurr', {project: item });
            // console.log("project",item,index);
            this.$store.commit('updateLoadingStatus', {isLoading: true});
            this.projectGet({id:this.proCurr.id,setting:1,task:1}).then(data=>{
                this.$store.commit('updateLoadingStatus', {isLoading: false});
                console.log("projectGet",data);
                var menuUserDic = {} ;
                menuUserDic[noneUser.fuid] = noneUser ;
                var len = data.members.length ;
                for(var i=0;i<= len-1 ;i++){
                    var item = data.members[i] ;
                    memberDic[item.fuid] = item ;
                    var tempn = { name:item.nname||item.username,show:"",undo:0,done:0,uid:item.fuid,value:item.fuid,key:"to",img:item.head, tasks:[]} ;
                    menuUserDic[item.fuid] = tempn ;  //数据库把字段修改成了fuid
                }                
                this.$store.commit('z39/membersAdd', {members: data.members});

                var menuTagDic = {} ;
                menuTagDic[noneTag.key] = noneTag ;

                let tagsArr = data.tagtmp.tmp.split(",") , tmptags=[] ,tempDepart=[];
                tagsArr.forEach((key,index)=>{ 
                    let menu = {key:key,show:"",undo:0,done:0,name:this.tagitemDic[key],value:'',img:'',tasks:[]} ;
                    tmptags[index] = menu;
                    menuTagDic[key] = menu ;
                    departDic[key] = {key:key,name:this.tagitemDic[key]};
                    tempDepart.push({key:key,name:this.tagitemDic[key]});
                    // console.log("tag menu: " , key,this.tagitemDic[key]);
                });
                this.tmptags = tmptags ;  //未分类任务设置标签使用.
                this.tagsArr = tagsArr ;  //判断是否包含项目标签,使用交集.
                this.menuTagDic = menuTagDic ;

                this.menuUserDic = menuUserDic ;
                this.members = data.members;
                this.$store.commit('z43/currMembers', {list: data.members});
                this.departs = tempDepart ;
            },data=>{
                this.$store.commit('updateLoadingStatus', {isLoading: false});
            }) ;

            this.pageIndex =1 ;
            this.pageShowNum = this.pageIndex * this.pageNumOne ;

            this.$nextTick(() => {
                try{this.$refs.scroll.enablePullup(),this.$refs.scroll.reset({top:0})}catch(e){}
            })
        },        
        actionOpenDone(item,index,option,index1){
            let dir = "" , target , arrIndex = index ;
            if(option == 1) target = this.$refs['actionUser'+index1][index] ;
            else target = this.$refs.action[index] ;
            dir = target.direction ;
            if( dir == "left"){
                if( item.state == "done"){
                    this.doTaskEdit(item,"");
                    this.tongji("task","cancelled","todo","swipe");
                }else{
                    this.doTaskEdit(item,"done",moment().format("YYYY-MM-DD HH:mm"));
                    this.tongji("task","done","todo","swipe");
                }
                setTimeout(() => {target.close()}, 200); //自动关闭
            }
        },
        actionOpen(item,index,option,index1){
            let dir = "" , target , arrIndex = index ;
            console.log("action open:",index,index1) ;
            if(option == 1){
                target = this.$refs['actionUser'+index1][index] ;
            }else {   //if(option == 2)
                target = this.$refs.action[index] ;
            }
            // return ;
            dir = target.direction ;
            if( dir == "left"){                
                //未分类,显示默认第一个成员或选择后的成员
                if( this.showMode == 'user' && !item.uid ){  
                    let val = this.memberSelect ;
                    // this.doTagSet(item,"to",val);
                    this.taskSet({id:item.id,uid:val},item);
                }else if(this.showMode == 'project' && index1 ==0 ){  //显示默认第一个部门 
                    let val = this.departSelect ;
                    this.doTagSet(item,val,"");
                }else{  //显示设置日期
                    let val = this.dueSelect ;
                    if( item.tags && (item.tags["due"] == undefined || (item.tags["due"] != undefined && item.tags["due"].indexOf(val) == -1)) ){  //没有设置过更详细的时间. 避免覆盖更精确的信息.
                        // this.doTaskEdit(item,"due",val);
                        this.doTagSet(item,"due",val,true);
                    }else{
                        this.$vux.toast.show({text: "已设置日期",type: "success"});
                    }
                }
                setTimeout(() => {target.close();}, 200); //自动关闭菜单
            }
        },
        goTask(item,index){ // 进入任务详情
            console.log( _.clone(item)) ;
            this.$router.push(`/taskDetail/${item.id}`) ;
        },
        doTask(item,index){ 
            //未分类,显示默认第一个成员或选择后的成员
            if( this.showMode == 'user' && !item.uid ){  
                let val = this.memberSelect ;
                // this.doTagSet(item,"to",val);
                this.taskSet({id:item.id,uid:val},item);
            }else if(this.showMode == 'project'){  //显示默认第一个部门 
                let val = this.departSelect ;
                this.doTagSet(item,val,"");
            }
        },
        onAction(item,index1){
            if (!event._constructed) return;  // 去掉自带click事件的点击
            if(this.longvisible) return ; //长按任务触发了事件.
            this.taskCurr = item ;
            if( this.showMode == 'user'){
                this.showMember = true ;                
            }else if(this.showMode == 'project' ){
                this.showDepart =true ;
            }
            console.log( _.clone(item)) ;
        },
        getData: function() {
        },
        _initScroll() {
            this.menuScroll && this.menuScroll.destroy();
            this.foodScroll && this.foodScroll.destroy();
            this.menuScroll = new BScroll(this.$refs.menuWrapper, {
              click: true
            });
            this.foodScroll = new BScroll(this.$refs.foodWrapper, {
              probeType: 3,
                deceleration: 0.001,
                bounce: false,
                swipeTime: 2000,
                click: true,
            });
            // this.foodScroll.scrollTo(0, 1);
            this.foodScroll.on('scroll', (pos) => {
              this.scrolly = Math.abs(Math.round(pos.y)) || 0;
              // console.log( "this.scrolly: ",this.scrolly,pos.y);
              if(this.useCpt) this.currentIndexCpt() ;
            });
          },
      _calculateHeight() {
        this.listHeight = [];
        let foodList = this.$refs.foodWrapper.getElementsByClassName('food-list-hook');
        let height = 0;
        this.listHeight.push(height);
        for (let i = 0; i < foodList.length; i++) {
          let item = foodList[i];
          height += item.clientHeight;
          this.listHeight.push(height);
        }
      },
      selectMenu(index, event) {
        if (!event._constructed) {
          // 去掉自带click事件的点击
          return;
        }
        // console.log("menu:",this.$refs.menu[index].getAttribute("tagkey") ) ;
        this.setMenu2Value(index);
        this.currentIndex = index ;  //优化点击按钮后闪动
        this.useCpt = false ;
        setTimeout(()=>{this.useCpt = true},1000);
        let foodList = this.$refs.foodWrapper.getElementsByClassName('food-list-hook');
        let el = foodList[index];
        this.foodScroll.scrollToElement(el, 300);
      },
      setMenu2Value(index) {
        if( index == this.currentIndex ){ //&& this.showMode == type 
            return ; //值没变化跳出
        }
        let value = this.$refs.menu[index] ;
        try{
            if( this.showMode == 'user'){
                this.uidSet = value.getAttribute("tagValue") ;
                this.keySet = "to" ;  //uidset 必须必 keyset先,只watch了keyset
            }else if( this.showMode == 'project'){
                this.uidSet = 0 ;
                this.keySet = value.getAttribute("tagkey") ;
            }
            this.keySetChange();
        }catch(e){}
        
        console.log("menu:",index,this.keySet,this.uidSet ) ;
      },
      incrementTotal(target) {
        this.$refs.shopCart.drop(target);
      },
        currentIndexCpt() {
            var index = 0  ;
            var scrolly = this.scrolly || 0 ;            
            for (let i = 0; i < this.listHeight.length; i++) {
              let height = this.listHeight[i];
              let height2 = this.listHeight[i + 1];
              if (!height2 || (scrolly >= height && scrolly < height2)) {
                index = i ;
                break ;
                // return i;
              }
            }
            this.setMenu2Value(index);
            this.currentIndex = index ;            
            // console.log("menu index:", index , this.scrolly ,this.listHeight.length,this.listHeight);
            return index;
          },
      refreshUser(task){
        // console.log("refresh", task.uid, _.clone(task)) ;
        var temp = [] ;
        for(var uid in this.menuUserDic){
            let tasks = this.menuUserDic[uid].tasks ;
            if(uid==0){   //从里面未分配tasks分配
                this.menuUserDic[uid].tasks = tasks.filter(item => task.id != item.id ) ;
            }else if(uid == task.uid){   //分配到的任务
                tasks.unshift(task) ;
                // console.log("refresh add", _.clone(task)) ;
            }
            temp.push(this.menuUserDic[uid]);
        }
        temp = _.sortBy(temp, function(item){ return Math.max(item.uid); });
        this.goods = temp ;
        return temp ;
      },
      refreshList(y){
          this.$nextTick(() => {
            this._initScroll();
            this._calculateHeight();
            if(y!=0) this.foodScroll.scrollTo(0, y ) ;
          }); 
      },
        showBtnTxt(item,index1){
            let txt = "" ,key="" ;
            if( this.showMode == 'user' && !item.uid ){  
                let val =this.memberSelect ;
                let people = this.menuUserDic[val]; //"uid_" + 
                txt = people?people.name:"无" ;
                if(people==undefined) console.log("no uid_" + val)
            }else if(this.showMode == 'project' && index1 ==0 ){  //显示默认第一个部门 
                key = this.departSelect ; 
                txt = this.tagitemDic[key] ;
            }else{  //显示设置日期
                txt = this.dueSelect  ;
                let todayStr = moment().format('YYYY-MM-DD') ;                
                if( txt == todayStr){
                    txt = "今天" ;
                }else if( txt == moment().add(1,"d").format('YYYY-MM-DD') ){
                    txt = "明天" ;
                }
            }
            // this.showBtnTxt = txt ;
            return txt ;
        },
        changePercent(doneAll,taskAll){
            console.log("changePercent");
            // var temp = this.todayArr ;
            // var tempDone = temp.filter(task=> {return task.state == 'done'} );
            // var doneNum = tempDone.length  ;
            this.taskPercent = taskAll>0?Math.floor(100*doneAll/taskAll):0;
            this.$vux.toast.show({
               text: `完成:${doneAll} 总数:${taskAll}`, position:'middle',width:"200px",time:3000,type:"text"});
        },
        onMember(item){
            let type ;
            if( item.key == "add" ){
                console.log("添加");
                type = this.editType == 0? "add":"new";
            }else if( item.key == "del" ){
                console.log("减少");
                type = "del"; 
                if( this.memberlist.length <= 1 ){  //如果没有用户,则直接进入添加成员
                    type = "add" ;
                }
            }
            if( this.editType == 0 ){ //新增
                this.go(`n_import`);
            }else{
                this.go(`n_import?gid=${this.proCurr.id}&type=${type}`);
            }
            // this.go("n_import/");
        },        
        loadNext(){
            console.log("loadNext");
            if( this.pageIndex < this.pageTotal ){
                this.pageIndex ++ ;
                this.pageShowNum = this.pageIndex * this.pageNumOne ;
                // console.log("pageShowNum",this.pageShowNum) ;
                this.$refs.scroll.donePullup() ;
            }
			this.checkClosePullup();
        },
		checkClosePullup(){
            this.$refs.scroll.reset();
			if( this.pageIndex >= this.pageTotal){
				setTimeout(() => {
					this.$refs.scroll.disablePullup()
				}, 100)	
			}
		},
        keySetChange(){
            let tags ={} ;
            let data ={tags,pid:this.proCurr.id}; 
            if( this.keySet == 'to'){
                if( this.uidSet != 0 ){
                    // tags.to = this.uidSet || this.uid ;
                    data.uid = this.uidSet || this.uid ;
                }
            }else{
                if( this.keySet != "" ) tags[this.keySet] = '' ;
            }
            this.taskAddExt = data ;
			this.$store.commit({ type: "z39/addTaskExt", value: data });
        },
        onTaskAdd(){
            if(this.$route.path.indexOf("m_task")==-1 && !this.uid && !localStorage.getItem('token')) return this.$vux && this.$vux.bus && this.$vux.bus.$emit('showlogin', true);
            this.showTaskAdd = true ;
        },
        taskAddVis(val){
            this.showTaskAdd = val ;
            if(!val) this.editType=-1;
        },
        ...mapActions([
            
        ])
    },
    data() {
        return {
            pageName:"project",
            inited:false ,
            editType:-1,
            btns: ["任务","项目"],
            taskTitle:"",
            taskDesc:"",
            proCurr: {},
            proCurrData: {title:"",key:"",desc:""},
            proTitle:"",
            proIndex: 0,
            prokey:"",
            proDesc:"",
            // protasks:[] ,
            visibility: false ,            
            goods: [],
            menuUserDic:null,
            menuTagDic:null,
            listHeight: [],
            scrolly: 0,
            selectedFood: {},
            currentIndex:0 ,
            showMode:'default',  // user default project
            showModes:[{name:"默认",value:"default"},{name:"成员",value:"user"},{name:"部门",value:"project"}],
            taskHeight:0, //(window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight) - 130
            members:[],
            tagsArr:[],
            tmptags:[],
            showMember:false ,
            showDepart:false,
            departs:[] ,
            taskDepart:[],
            taskMember:[],
            taskCurr:null,
            keySet:'to', //uidset 必须必 keyset先赋值,只watch了keyset
            uidSet:0,
            dueSelect:"",
            memberSelect:"",
            departSelect:"",
            taskTouch:null,
            taskTouchIndex:0,
            taskPercent:0,
            defaultHead:"/static/z39h5/img/logo.png",
            memberBtn:[{name:"",head:"/static/z39h5/img/add.png",key:"add"},{name:"",head:"/static/z39h5/img/reduce.png",key:"del"},],
            memberlist:[], //{name:"张1",head:""},{name:"张2",head:""},{name:"张3",head:""},{name:"张4",head:""},{name:"张5",head:""},{name:"张6",head:""},{name:"张7",head:""},{name:"张8",head:""},
            // showBtnTxt:"",
            pageIndex: 1 ,
            pageTotal: 2 ,
            pageShowNum:15,
            pageNumOne: 15 ,
              pullupConfig2: {
                content: '上拉加载更多',
                downContent: '松开进行加载',
                upContent: '上拉加载更多',
                loadingContent: '加载中...'
              },
            pullStatus: {
             pullupStatus: 'default',
             pulldownStatus: 'default'
            },
            pullDownConfig2: {
                content: '松开切换模式',
                downContent: 'VIP高级模式',
                upContent: '下拉进入高级模式',
                loadingContent: '切换中...'
              },
            scrollHeight:"-129",
            tasksLen:0,
            tasksLenStr:"0",
            showTaskAdd:false,
            taskAddExt:{},
            useCpt:true,
        }
    }
}

</script>
<style scoped>

.day-item {
  border: 1px solid #ececec;
  padding: 5px 15px;
}
.day-item-selected {
  border: 1px solid green;
}

#p_timepro .vux-button-group{
    background-color: #fff; 
    padding-top: 1px;
}
#p_timepro .vux-tab {
    padding:2px 6px ;
    height: 32px;
}
#p_timepro .vux-tab .vux-tab-item{
    background: #fff;
    line-height: 28px;    font-size: 16px;
}
#p_timepro .vux-tab .vux-tab-selected {
    background: rgba(0, 169, 255, 0.24);border-radius: 6px;
}

.checkScroll{max-height: 300px;min-height: 120px;    overflow: scroll;}
.demo1-item {
        border: 1px solid #027ab7;
    border-radius: 4px;
    padding: 0 6px 4px 4px;
    min-width: 40px;
    line-height: 31px;
    height: 31px;
    width: auto;
    text-align: center;
    font-size: 12px;
}

.demo1-item-selected {
    border: 1px solid #8e8e8e;
    background-color: #10aeff;
}

</style>
<style>

#p_timepro .weui-search-bar:before {
    height: 0;
    border-top: 0;
}
/*#p_timepro .vux-tab .vux-tab-item{
    background: #fff;
}*/
#p_timepro .day  .vux-tab-selected {
    background: #eee;
    border-radius: 4px;
}

.good {
  display: -ms-flexbox;
  display: flex;
  position: relative ;
  /*position: absolute;
  top: 77px;
  bottom: 46px;*/
  width: 100%;
  overflow: hidden;
}
.good .menu-wrapper {
  -ms-flex: 0 0 80px;
      flex: 0 0 80px;
  width: 80px;
  background: #f3f5f7;
}
.good .menu-wrapper .menu-item {
  display: table;
  /*width: 56px;*/
  height: 54px;
  line-height: 14px;
  padding: 4px 12px;
}
.good .menu-wrapper .menu-item.current {
  position: relative;
  z-index: 10;
  margin-top: -1px;
  background: #fff;
  border-left: 3px solid #10aeff;
  padding-left: 9px;
  /*font-weight: 700;*/    
  color: #10aeff;
}
.good .menu-wrapper .menu-item.current .iconMenu{
    color: #fff;
}
.good .menu-wrapper .menu-item.current .text:after {
  display: none;
}
.good .menu-wrapper .menu-item .icon {
  display: inline-block;
  width: 12px;
  height: 12px;
  vertical-align: top;
  margin-right: 4px;
  background-size: 12px 12px;
  background-repeat: no-repeat;
}
.good .menu-wrapper .menu-item .text {
  display: table-cell;
  width: 56px;
  vertical-align: middle;
  position: relative;
  font-size: 12px;
  padding-bottom: 4px;
}
.good .menu-wrapper .menu-item .text:after {
  display: block;
  position: absolute;
  left: 0;
  bottom: 0;
  border-top: 1px solid rgba(7,17,27,0.1);
  width: 100%;
  content: '';
}
.good .foods-wrapper {
  -ms-flex: 1;
      flex: 1;
}
.good .foods-wrapper .food-list .title {
  padding-left: 14px;
  height: 26px;
  line-height: 26px;
  border-left: 2px solid #d9dde1;
  font-size: 12px;
  color: #93999f;
  background: #f3f5f7;
}
.good .foods-wrapper .food-list .food-item {
  display: -ms-flexbox;
  display: flex;
  margin: 12px;
  padding-bottom: 12px;
  position: relative;
}
.good .foods-wrapper .food-list .food-item:after {
  display: block;
  position: absolute;
  left: 0;
  bottom: 0;
  border-top: 1px solid rgba(7,17,27,0.1);
  width: 100%;
  content: '';
}
.good .foods-wrapper .food-list .food-item:last-child {
  margin-bottom: 0px;
}
.good .foods-wrapper .food-list .food-item:last-child:after {
  display: none;
}
.good .foods-wrapper .food-list .food-item .icon {
  -ms-flex: 0 0 57px;
      flex: 0 0 57px;
  margin-right: 10px;
}
.good .foods-wrapper .food-list .food-item .content {
  -ms-flex: 1;
      flex: 1;
}
.good .foods-wrapper .food-list .food-item .content .name {
  margin: 2px 0 0 0;
  font-size: 14px;
  line-height: 14px;
  height: 14px;
  color: #07111b;
      overflow: hidden;
    display: -webkit-box;
    -webkit-line-clamp: 1;
    -webkit-box-orient: vertical;
    word-break: break-all;
}
.good .foods-wrapper .food-list .food-item .content .desc,
.good .foods-wrapper .food-list .food-item .content .extra {
  font-size: 10px;
  line-height: 10px;
  color: #93999f;
}
.good .foods-wrapper .food-list .food-item .content .desc {
  margin-top: 8px;
  line-height: 12px;
      overflow: hidden;
    display: -webkit-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
    word-break: break-all;
}
.good .foods-wrapper .food-list .food-item .content .extra .count {
  margin-right: 12px;
}
.good .foods-wrapper .food-list .food-item .content .price {
  font-weight: 700px;
  line-height: 24px;
}
.good .foods-wrapper .food-list .food-item .content .price .now {
  margin-right: 8px;
  font-size: 14px;
  color: #f01414;
}
.good .foods-wrapper .food-list .food-item .content .price .old {
  font-size: 10px;
  color: #93999f;
  text-decoration: line-through;
}
.good .foods-wrapper .food-list .food-item .content .cartControl-wrapper {
  position: absolute;
  right: 0;
  bottom: 12px;
}
li{
    list-style: none;
}
.food-list{ background-color: #fff;}   

#p_timepro .weui-grids .weui-grid__icon{width: 50px;height: 50px;}
#p_timepro .weui-grids>a {padding: 4px 4px;}
#p_timepro .weui-grid:before,.weui-grid:after{border-bottom:0;border-right:0;}

#p_timepro .taskCount{background-color:#10aeff87}
#p_timepro .task_going .taskCount,#p_timepro .task_cancle .taskCount{color: #000000}

</style>
